package base;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import negocio.NegocioException;



/**
 * Formulario Bean do caso de uso - Formulario base.
 * @author Fernando Franzini
 * @author Edson Bernardo
 */

public abstract class FormularioBase {

	protected final void imprimirErrosPagina(String[] erros) {
		FacesContext context = FacesContext.getCurrentInstance();
		for (String erro : erros) {
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, erro, ""));
		}
	}

	protected final void imprimirErrosPagina(NegocioException ex) {
		imprimirErrosPagina(ex.getErrosString());
	}

	protected final void imprimirErrosPagina(String erro) {
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
				erro, ""));
	}

	protected final Object getObjetoRequest(String key) {
		ExternalContext ct = FacesContext.getCurrentInstance()
				.getExternalContext();
		return ct.getRequestMap().get(key);
	}

	protected final String getParametrosRequest(String key) {
		ExternalContext ct = FacesContext.getCurrentInstance()
				.getExternalContext();
		return (String) ct.getRequestParameterMap().get(key);
	}

	public final HttpServletResponse getResponse() {
		return (HttpServletResponse) FacesContext.getCurrentInstance()
				.getExternalContext().getResponse();
	}

	@SuppressWarnings("unchecked")
    protected <T> T getManagedBean(String bean, Class<T> c) {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExpressionFactory e = fc.getApplication().getExpressionFactory();
		ValueExpression valueExpression = e.createValueExpression(fc.getELContext(),"#{"+bean+"}",c);
		T mnb = (T) valueExpression.getValue(fc.getELContext());
		return mnb;
    }	
	
	protected final HttpSession getSessao() {
		ExternalContext ct = FacesContext.getCurrentInstance()
				.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ct.getRequest();
		return request.getSession();
	}

	public final String getContextPath() {
		ExternalContext ct = FacesContext.getCurrentInstance()
				.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ct.getRequest();
		return request.getSession().getServletContext().getRealPath("/");
	}
}
